import { useState, useEffect } from 'react';
import api from '../api/axiosConfig';
import { Work } from '../types'; // 假设 Work 类型已在 types.ts 中定义

const AdminApprovalPage = () => {
  const [pendingWorks, setPendingWorks] = useState<Work[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [message, setMessage] = useState('');

  useEffect(() => {
    const fetchPendingWorks = async () => {
      try {
        // 请求我们之前创建的、只有管理员能访问的接口
        const { data } = await api.get('/works/pending');
        setPendingWorks(data);
      } catch (err) {
        setError('无法加载待审核列表。');
      } finally {
        setLoading(false);
      }
    };
    fetchPendingWorks();
  }, []);

  const handleApprove = async (workId: string) => {
    setMessage('');
    try {
      // 调用批准作品的接口
      await api.patch(`/works/${workId}/approve`);

      // 在前端立即移除已批准的作品，提供更好的用户体验
      setPendingWorks(currentWorks => currentWorks.filter(work => work._id !== workId));
      setMessage('作品已批准！');

    } catch (err) {
      setMessage('操作失败，请重试。');
    }
  };

  if (loading) return <p>加载中...</p>;
  if (error) return <p style={{ color: 'red' }}>{error}</p>;

  return (
    <div style={{ maxWidth: '900px', margin: '0 auto' }}>
      <h2>作品审核</h2>
      {message && <p style={{ color: 'green' }}>{message}</p>}
      {pendingWorks.length === 0 ? (
        <p>没有需要审核的作品。</p>
      ) : (
        <ul style={{ listStyle: 'none', padding: 0 }}>
          {pendingWorks.map(work => (
            <li key={work._id} style={{ border: '1px solid #ddd', padding: '1rem', marginBottom: '1rem' }}>
              <h3>{work.title}</h3>
              <p>所属小队: {work.team?.name || '未知'}</p>
              <p>{work.description}</p>
              <button onClick={() => handleApprove(work._id)}>批准</button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default AdminApprovalPage;